import AddCinema from "./add.js";
import Seat from "./seat.js";
let $ = layui.$;
export default class Cinemas {
    constructor() {
        this.render()
        this.handel()
    }
    render() {
        let template = `
        <style>

        .seat_optional,
        .seat_null {
            display: block;
            height: 10px;
            width: 10px;
            margin: 2px;
        }


        .seat_optional {
            background-color: red;
        }

        .seat_null {
            background-color: transparent;
        }
    </style>
            <h1 style="padding: 15px;">院线管理</h1>
            <div style="display:flex">
            <div class="layui-btn-group">
                <button type="button" id="addBtn" class="layui-btn layui-btn-sm">
                    <i class="layui-icon">&#xe654;</i>
                </button>
            </div>
            <form class="layui-form" lay-filter="searchForm">
                <div class="layui-form-item" style="display:flex">
                    <div class="layui-input-block" style="width:200px;display:block">
                        <select name="opt" lay-filter="aihao">
                            <option value="name">院线名</option>
                            <option value="addr">院线地址</option>
                            <option value="tel">官方电话</option>
                            <option value="url">官方网站</option>
                        </select>
                    </div>
                    <input type="text" name="text" lay-verify="title" autocomplete="off" placeholder="查询内容为空默认查询所有" class="layui-input">
                    <button type="submit" class="layui-btn" lay-submit="" lay-filter="search">搜索</button>
                </div>
            </form>
        </div>
        <table id="cinemaTable" lay-filter="cinemaTable"></table>
        <script type="text/html" id="cinemaBar">
            <a class="layui-btn layui-btn-xs" lay-event="edit">修改</a>
            <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
        </script>    
        <script type="text/html" id="addCinemaTemplate"></script>
        <script type="text/html" id="updateCinemaTemplate"></script>
        `;
        $("#content").html(template);
    }
    handel() {
        new AddCinema();
        let table = layui.table;
        let form = layui.form;
        let dataId;
        let index = 0;
        form.render();
        table.render({
            elem: "#cinemaTable",
            url: "/api/cinemas", //数据接口
            page: {
                //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ["limit", "count", "prev", "page", "next", "skip"], //自定义分页布局
                //,curr: 5 //设定初始在第 5 页
                groups: 5, //只显示 5 个连续页码
                first: "首页", //不显示首页
                last: "尾页", //不显示尾页
                limits: [1, 3, 5, 10, 15, 20],
                limit: 5,
            },
            cols: [
                [
                    { field: "name", title: "院线名" },
                    { field: "addr", title: "院线地址", sort: true },
                    { field: "tel", title: "官方电话", sort: true },
                    { field: "url", title: "官方网站", sort: true },
                    {
                        field: "screens", title: "放映厅",
                        templet: (d) => {
                            let str = '';
                            for (let s of d.screens) {
                                str += `<span class="seat" data-seat="${JSON.stringify(s.seat)}" style="cursor:pointer">${s.name}</span>,`;
                            }
                            // console.log(d);
                            return str;
                        }
                    },
                    { fixed: "right", title: "操作", toolbar: "#cinemaBar" },
                ],
            ],
            parseData: function (res) {
                //res 即为原始返回的数据
                return {
                    code: 0, //解析接口状态
                    msg: "", //解析提示文本
                    count: res.total, //解析数据长度
                    data: res.rows, //解析数据列表
                };
            },
            request: {
                pageName: "current", //页码的参数名称，默认：page
                limitName: "size", //每页数据量的参数名，默认：limit
            },
            done() {
                $(".seat").click(function () {
                    // console.log($(this).attr("data-seat"));
                    new Seat($(this).attr("data-seat"));
                })
            }
        });

        //修改，删除
        //监听工具条
        table.on('tool(cinemaTable)', function (obj) {
            var data = obj.data;
            dataId = data._id;
            if (obj.event === 'del') {
                layer.confirm('真的删除行么', function (index) {
                    $.ajax({
                        type: 'delete',
                        url: `/api/cinemas/${data._id}`,
                        success() {
                            layer.close(index);
                            table.reload('cinemaTable', { page: { curr: 1 } });
                        }
                    })
                });
            } else if (obj.event === 'edit') {
                // console.log(1111);
                let template = `
            <form  class="layui-form" lay-filter="updateForm">
            <div class="layui-form-item">
            <label class="layui-form-label">院线名称</label>
            <div class="layui-input-block">
                <input
                type="text"
                name="name"
                required
                lay-verify="required"
                placeholder="请输入院线名称"
                autocomplete="off"
                class="layui-input"
                />
            </div>
            </div>
            <div class="layui-form-item">
            <label class="layui-form-label">地址</label>
            <div class="layui-input-block">
                <input
                type="text"
                name="addr"
                required
                lay-verify="required"
                placeholder="请输入地址"
                autocomplete="off"
                class="layui-input"
                />
            </div>
            </div>
            <div class="layui-form-item">
            <label class="layui-form-label">电话</label>
            <div class="layui-input-block">
                <input
                type="text"
                name="tel"
                required
                lay-verify="required"
                placeholder="请输入电话"
                autocomplete="off"
                class="layui-input"
                />
            </div>
            </div>
            <div class="layui-form-item">
            <label class="layui-form-label">官方网址</label>
            <div class="layui-input-block">
                <input
                type="text"
                name="url"
                required
                lay-verify="required|url"
                placeholder="请输入官方网址"
                autocomplete="off"
                class="layui-input"
                />
            </div>
            </div>
            <div  class="layui-input-block">
            <button id="addScreenBtn" type="button" class="layui-btn layui-btn-normal layui-btn-radius" >增加放映厅</button>
            </div>
            <div id="screensDiv">
                
            </div>
            <button lay-submit id="submitForm2" lay-filter="submitForm2"  style="display:none">提交</button>
            </form>
        `;
                $("#updateCinemaTemplate").html(template);
                layer.open({
                    type: 1,
                    title: "修改院线", //不显示标题栏
                    area: ["800px", "400px"],
                    shade: 0.6,
                    id: "LAY_layuipro", //设定一个id，防止重复弹出
                    btn: ["确认", "取消"],
                    btnAlign: "c",
                    moveType: 1, //拖拽模式，0或者1
                    content: $("#updateCinemaTemplate").html(),
                    yes() {
                        $("#submitForm2").click();
                    },
                    success: function (layero) {
                        $.ajax({
                            type: "get",
                            url: `/api/cinemas/${data._id}`,
                            success(res) {
                                let screensArr = res.screens;
                                index = screensArr.length;
                                for (let i = 0; i < screensArr.length; i++) {
                                    let screenStr = `
                <div id="screenDiv${i}" class="screenDiv" style="border:1px dashed;margin:10px;padding:10px">
                    <div class="layui-form-item">
                    <label class="layui-form-label">放映厅名</label>
                    <div class="layui-input-block">
                        <input
                        type="text"
                        id="screenName${i}"
                        required
                        lay-verify="required"
                        placeholder="请输入放映厅名"
                        autocomplete="off"
                        class="layui-input"
                        />
                    </div>
                    </div>
                    <div class="layui-form-item">
                    <label class="layui-form-label">座位排列</label>
                    <div class="layui-input-block">
                        <input
                        type="text"
                        id="seat${i}"
                        required
                        lay-verify="required|judgearr"
                        placeholder="请输入排列"
                        autocomplete="off"
                        class="layui-input"
                        />
                    </div>
                    </div>
                    <div class="layui-form-item">
                    <div class="layui-input-inline">
                    <button type="button" data-index="${i}" class="layui-btn layui-btn-xs layui-btn-warm layui-btn-radius show-seat-btn">查看</button>
                    <button type="button" data-index="${i}" class="layui-btn layui-btn-xs layui-btn-danger layui-btn-radius del-seat-btn">删除</button>
                    </div>
                    </div>
                </div>
                `;
                                    $("#screensDiv").append(screenStr);
                                    //渲染影厅信息
                                    $(`#screenName${i}`).val(screensArr[i].name);
                                    $(`#seat${i}`).val(JSON.stringify(screensArr[i].seat));
                                }
                                form.val('updateForm', res);
                                form.render();
                            }
                        });
                        //点击预览
                        $("#screensDiv").on("click", ".show-seat-btn", function () {
                            let index = $(this).attr("data-index");
                            new Seat($("#seat" + index).val());
                        });
                        //点击删除
                        $("#screensDiv").on("click", ".del-seat-btn", function () {
                            let index = $(this).attr("data-index");
                            $("#screenDiv" + index).remove();
                        });
                        // 给增加放映厅按钮添加事件
                        $("#addScreenBtn").click(function () {
                            //获取当前放映厅大小
                            // console.log($("#screensDiv").children('div.screenDiv').length);
                            index = $("#screensDiv").children('div.screenDiv').length;
                            let screenStr = `
                <div id="screenDiv${index}" style="border:1px dashed;margin:10px;padding:10px">
                    <div class="layui-form-item">
                    <label class="layui-form-label">放映厅名</label>
                    <div class="layui-input-block">
                        <input
                        type="text"
                        id="screenName${index}"
                        required
                        lay-verify="required"
                        placeholder="请输入放映厅名"
                        autocomplete="off"
                        class="layui-input"
                        />
                    </div>
                    </div>
                    <div class="layui-form-item">
                    <label class="layui-form-label">座位排列</label>
                    <div class="layui-input-block">
                        <input
                        type="text"
                        id="seat${index}"
                        required
                        lay-verify="required|judgearr"
                        placeholder="请输入排列"
                        autocomplete="off"
                        class="layui-input"
                        />
                    </div>
                    </div>
                    <div class="layui-form-item">
                    <div class="layui-input-inline">
                    <button type="button" data-index="${index}" class="layui-btn layui-btn-xs layui-btn-warm layui-btn-radius show-seat-btn">查看</button>
                    <button type="button" data-index="${index}" class="layui-btn layui-btn-xs layui-btn-danger layui-btn-radius del-seat-btn">删除</button>
                    </div>
                    </div>
                </div>
                `;
                            index++;
                            $("#screensDiv").append(screenStr);
                        });
                    }
                });
            }
        });

        form.on("submit(submitForm2)", function (data) {
            let screens = [];
            for (let i = 0; i < index; i++) {
                if ($("#screenDiv" + i).length > 0) {
                    screens.push({
                        name: $("#screenName" + i).val(),
                        seat: JSON.parse($("#seat" + i).val())
                    });
                }
            }
            // console.log(screens);
            $.ajax({
                type: "put",
                url: `/api/cinemas/${dataId}`,
                // async: false,
                data: { ...form.val("updateForm"), screens: JSON.stringify(screens) },
                success() {
                    table.reload("cinemaTable");
                },
            });
            layer.closeAll();
        });

        //搜索
        form.on('submit(search)', function (data) {
            let obj = {};
            if (!!data.field.text) {
                obj = data.field;
            }
            table.reload('cinemaTable', {
                page: {
                    curr: 1
                }, where: obj
            });
            return false;
        });
        form.verify({
            judgearr(value, item) {
                // let reg = /^[A-Za-z0-9]+$/;
                // // console.log(reg.test(value));
                // if (!reg.test(value)) {
                //     let str = JSON.parse(value);
                //     // console.log(str, typeof (str));
                //     if ((str instanceof Array) && (str.length > 0)) {
                //         for (let it of str) {
                //             // console.log(it, typeof (it));
                //             if (it instanceof Array) {

                //             } else {
                //                 return '排列有误！！'
                //             }
                //         }
                //     } else {
                //         return '排列有误！！'
                //     }
                // } else {
                //     return '排列有误！！'
                // }
                try {
                    let str = JSON.parse(value);
                    // console.log(str, typeof (str));
                    if ((str instanceof Array) && (str.length > 0)) {
                        for (let it of str) {
                            // console.log(it, typeof (it));
                            if (it instanceof Array) {

                            } else {
                                return '排列有误！！'
                            }
                        }
                    } else {
                        return '排列有误！！'
                    }
                } catch (err) {
                    return '排列有误！！'
                }
            }
        });
    }
}